import os
import tkinter
import tkinter.simpledialog
import tkinter.colorchooser
import tkinter.filedialog
# 需要执行 pip install pillow 安装拓展库
from PIL import ImageGrab

root = tkinter.Tk()
root.title('MY Paint----by Dong Fuguo')
root.geometry('800x600')  # 使用 geometry 方法设置窗口大小

# 控制是否允许画图的变量，1：允许，0：不允许
CanDraw = tkinter.IntVar(value=0)

# 控制画图类型变量，1：画笔，2：直线，3：矩形，4：文本，5：橡皮
what = tkinter.IntVar(value=1)

# 记录鼠标位置的变量
X = tkinter.IntVar(value=0)
Y = tkinter.IntVar(value=0)

# 前景色，背景色
foreColor = '#000000'
backColor = '#ffffff'

# 创建画布
canvas = tkinter.Canvas(root, bg='white', width=800, height=600)
canvas.pack()

# 鼠标左键单击，允许画图，并记录当前鼠标位置
def onLeftButtonDown(event):
    CanDraw.set(1)
    X.set(event.x)
    Y.set(event.y)
    if what.get() == 4:
        text = tkinter.simpledialog.askstring("输入文本", "请输入要绘制的文本")
        if text:
            canvas.create_text(event.x, event.y, text=text, fill=foreColor)

canvas.bind('<Button-1>', onLeftButtonDown)

# 记录最后绘制图形的id
lastDraw = 0

# 按住鼠标左键移动，画图
def onLeftButtonMove(event):
    global lastDraw
    if CanDraw.get() == 0:
        return
    if what.get() == 1:
        # 使用当前选择的前景色绘制曲线
        canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor)
    elif what.get() == 2:
        # 绘制直线，先删除刚刚画过的直线，再画新的直线
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw = canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=foreColor)
    elif what.get() == 3:
        # 绘制矩形，先删除刚刚画过的矩形，再画新的矩形
        try:
            canvas.delete(lastDraw)
        except Exception as e:
            pass
        lastDraw = canvas.create_rectangle(X.get(), Y.get(), event.x, event.y, outline=foreColor)
    elif what.get() == 4:
        # 文本已经在鼠标单击时处理
        pass
    elif what.get() == 5:
        # 橡皮擦，使用背景色绘制
        canvas.create_line(X.get(), Y.get(), event.x, event.y, fill=backColor, width=10)
    
    X.set(event.x)
    Y.set(event.y)

canvas.bind('<B1-Motion>', onLeftButtonMove)

# 启动消息循环
root.mainloop()